package core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {
	private static void zip(ZipOutputStream out, File f, String base) throws IOException {
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			if ( base.length() > 0 ) {
				out.putNextEntry(new ZipEntry(base + "/"));
			}
			
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else {
			out.putNextEntry(new ZipEntry(base));
			FileInputStream in = new FileInputStream(f);

			try {
				int b;
				while ((b = in.read()) != -1) {
					out.write(b);
				}
			} finally {
				in.close();
			}
		}
	}

	private static void zipFileImpl(String zipFile, String path) throws IOException {
		FileOutputStream fos = null;
		ZipOutputStream out = null;

		try {
			fos = new FileOutputStream(zipFile);
			out = new ZipOutputStream(fos);
			File f = new File(path);
			zip(out, f, "");
			out.flush();

		} finally {
			if (out != null) {
				out.close();
			} else if (fos != null) {
				fos.close();
			}
		}
	}

	public static void zipFile(String zipFile, String path) {
		try {
			zipFileImpl(zipFile, path);
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public static void deleteFile(String dir) {
		File f = new File(dir);
		if (f.isDirectory()) {
			File[] delF = f.listFiles();
			if (delF.length > 0) {
				for (File fd : delF) {
					deleteFile(fd.getAbsolutePath());
				}
			}
		}

		f.delete();
	}
}
